/**
 * 
 */
package cas.server.ldap.authe.compare;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.ldaptive.Credential;

/**
 * @author Cre.Gu
 *
 */
public class DefaultCredentialCompareManager implements
		CredentialCompareManager {

	private final List<StringCredentialCompare> compareList;

	public DefaultCredentialCompareManager(
			final StringCredentialCompare... compares) {
		this(Arrays.asList(compares));
	}

	public DefaultCredentialCompareManager(
			List<StringCredentialCompare> compares) {
		this.compareList = new LinkedList<StringCredentialCompare>();
		compareList.addAll(compares);
	}

	@Override
	public boolean compare(Credential credential, byte[] stored) {
		try {
			return compareInternal(credential.getString(), stored);
		} catch (Exception e) {
			return false;
		}
	}

	protected boolean compareInternal(String string, byte[] stored) {
		for (StringCredentialCompare compare : compareList) {
			boolean flag = compare.compare(string, stored);

			if (flag)
				return flag;
		}

		return false;
	}
}
